package com.baoxin.chenxixc4coach;

import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baoxin.chenxixc4coach.adapter.AudioAdapter;
import com.baoxin.chenxixc4coach.bean.AudioCourse;
import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.NetUtil;
import com.baoxin.chenxixc4coach.utils.TimeTools;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class AudioCourseActivity extends BaseActivity implements AudioAdapter.OnAudioEditListener, AudioAdapter.OnAudioClickListener {

    private RecyclerView recyclerView;
    private AudioAdapter adapter;
    private List<AudioCourse> audioList;
    private MediaPlayer mp;

    private TextView mTitle;
    private TextView mCurrentProgress;//当前
    private TextView mMaxLength;//总长
    private int pos;//选中音频在list中position

    private SeekBar mSeekBar;
    private int currentPosition;//当前音乐播放的进度
    private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。
    private Timer timer;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_course);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mp = new MediaPlayer();

        mTitle = findViewById(R.id.currentTitle);
        mCurrentProgress = findViewById(R.id.progress);
        mMaxLength = findViewById(R.id.length);
        mSeekBar = findViewById(R.id.seek_bar);

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBarChanging = true;
                mCurrentProgress.setText(TimeTools.getHHmmssByLong(seekBar.getProgress()));
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekBarChanging = false;
                mp.seekTo(seekBar.getProgress());

            }
        });

        recyclerView = findViewById(R.id.recyclerview);
        adapter = new AudioAdapter(this, this);
        audioList = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(adapter);

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case Msg.REQUEST_SUCCEED:
                        audioList = (List<AudioCourse>) msg.obj;
                        adapter.setData(audioList);
                        adapter.notifyDataSetChanged();
                        if (audioList.size() == 0) {
                            pos = -1;
                        } else {
                            pos = 0;
                        }
                        break;
                }
            }
        };

        request();
    }

    /**
     * 添加课程
     *
     * @param view
     */
    public void onAdd(View view) {
        Intent intent = new Intent(this, AudioRecordActivity.class);
        startActivity(intent);
    }

    @Override
    public void onAudioEdit(int pos) {

    }

    private void request() {

        try {
            NetUtil.get(activity, Interfaces.URL_LIST_AUDIO, new MyCallback(Interfaces.URL_LIST_AUDIO, handler));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void initUI() {
        mTitle.setText(audioList.get(pos).getAuName());
        mCurrentProgress.setText("00:00:00");
        mMaxLength.setText(TimeTools.getHHmmssByLong(mp.getDuration()));
    }

    @Override
    public void onAudioClick(int pos) {
        this.pos = pos;
        play();

    }

    /**
     * 上一个
     *
     * @param view
     */
    public void onPre(View view) {
        if (pos <= 0) {
            Toast.makeText(activity, "没有了！", Toast.LENGTH_SHORT).show();
            return;
        } else {
            pos--;
        }
        play();
    }


    /**
     * 播放当前
     *
     * @param view
     */
    public void onPlay(View view) {
        if (pos == -1) {
            return;
        }
        play();
    }

    /**
     * 下一个
     *
     * @param view
     */
    public void onNext(View view) {
        if (pos == audioList.size() - 1) {
            Toast.makeText(activity, "没有了！", Toast.LENGTH_SHORT).show();
            return;
        } else {
            pos++;
        }
        play();
    }

    private void play() {

        mp.reset();

        AudioCourse currentAudio = audioList.get(pos);
        try {
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setDataSource(currentAudio.getAuUrl());
            mp.prepareAsync();
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initUI();
                        }
                    });
                    mp.start();
                    mp.seekTo(currentPosition);
                    mSeekBar.setMax(mp.getDuration());
                }
            });


            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (!isSeekBarChanging) {
                        mSeekBar.setProgress(mp.getCurrentPosition());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mCurrentProgress.setText(TimeTools.getHHmmssByLong(mp.getCurrentPosition()));
                            }
                        });

                    }
                }
            }, 0, 50);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "播放错误！", Toast.LENGTH_LONG).show();
        }
    }


    private void pause(){

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mp != null) {
            mp.stop();
            mp.release();
            mp = null;
        }
    }

}
